#include "GameManager.h"
#include "InputManager.h"
#include "../GameObjects/Player.h"
#include "../Maps/TerrainType.h"
#include "../Maps/Forest.h"
#include "../Maps/Weather.h"

GameManagerPtr GameManager::singleton;

GameManagerPtr GameManager::getSingleton()
{
	if(singleton == nullptr)
		singleton = std::make_shared<GameManager>();
	return singleton;
}

GameManager::GameManager()
	: quit_(false)
{
}

GameManager::~GameManager()
{
}

void GameManager::init(int argc, char **argv)
{
	TCODConsole::initRoot(100, 80, "Trefall's Roguelike", false, TCOD_RENDERER_GLSL);
	TCODConsole::root->setAlignment(TCOD_CENTER);
	TCODConsole::root->clear();

	map_viewport = Vec2i(90, 50);
	story_viewport = Vec2i(90, 20);
	map_console = std::make_shared<TCODConsole>(map_viewport.x(), map_viewport.y());
	story_console = std::make_shared<TCODConsole>(story_viewport.x(), story_viewport.y());
	story_console->setAlignment(TCOD_LEFT);

	map_console->clear();
	story_console->clear();

	//Construct
	input_mgr = std::make_shared<InputManager>();
	player = std::make_shared<Player>();
	terrain_type_mgr = std::make_shared<TerrainTypeManager>();
	forest = std::make_shared<Forest>(400, 400);
	weather = std::make_shared<Weather>();

	//Initialize
	player->init();
	forest->init();

	input_mgr->setKeyCallback(TCODK_ESCAPE, 0, [this](TCOD_key_t input) { this->quit(); });
}

void GameManager::run()
{
	while(TCODConsole::isWindowClosed() == false && quit_ == false)
	{
		story_console->clear();
		float dt = TCODSystem::getLastFrameLength();

		input_mgr->handleKeys();
		weather->update(dt);
		forest->update();
		player->update();

		forest->render();
		player->render();
		TCODConsole::blit(map_console.get(), 0, 0, 90, 50, TCODConsole::root, 5,5);
		TCODConsole::blit(story_console.get(), 0, 0, 90, 20, TCODConsole::root, 5,5+50);
		TCODConsole::flush();
	}
}

